package com.ctsi.commons.util.async;

import com.ctsi.commons.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 为jdk线程池建立线程,主要是可以对线程命名
 * 
 * @author yueming
 * 
 */
public class PoolThreadFactory implements ThreadFactory, UncaughtExceptionHandler {
	private static final AtomicInteger poolNumber = new AtomicInteger(1);
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	/** 守护状态. */
	private final boolean daemon;

	private final int priority;
	private final String namePrefix;

	private final static Logger logger = LoggerFactory.getLogger(PoolThreadFactory.class);

	public PoolThreadFactory(String threadName, boolean daemon,int priority) {
		namePrefix = StringUtil.concatString("PoThr-" ,String.valueOf(poolNumber.getAndIncrement()) , "-",threadName,"-");
        this.priority=priority;
		this.daemon = daemon;
	}
	public PoolThreadFactory(String threadName, boolean daemon ) {
        this(threadName,daemon,Thread.NORM_PRIORITY);
	}
	public static PoolThreadFactory getPoolThreadFactory(String threadName, boolean daemon){
		return new PoolThreadFactory(threadName,   daemon);
	}
	@Override
	public void uncaughtException(Thread thread, Throwable throwable) {
		logger.error("Uncaught Exception in thread " + thread.getName(), throwable);
	}
    @Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
		t.setDaemon(this.daemon);
		t.setPriority(priority);
		t.setUncaughtExceptionHandler(this);
		return t;
	}

}
